package eclipse.lib.graphics.primitives;
import com.sun.opengl.util.texture.*;
import javax.media.opengl.*;
/**
 * A basic GL API wrapper that handles multiple polygons of the GLPolygon class.
 *
 */
public class GLObject 
{
	private int polygonCount;
	private boolean beginDraw = true;
	private boolean endDraw = true;
	private GLPolygon polygon[];
	/**
	 * Sets the texture of one of the polygons
	 * @param pIndex Index of the polygon 
	 * @param texture Texture to use
	 */
	public void setTexture(int pIndex, Texture texture)
	{
		polygon[pIndex].setTexture(texture);
	}
	/**
	 * Returns the texture a polygon is using
	 * @param pIndex Polygon index
	 * @return Texture the polygon was using
	 */
	public Texture getTexture(int pIndex)
	{
		return polygon[pIndex].getTexture();
	}
	/**
	 * Sets the total number of polygons
	 * @param polygonCount Total number of polygons that make up the object
	 */
	public void setPolygonCount(int polygonCount)
	{
		this.polygonCount = polygonCount;
		polygon = new GLPolygon[polygonCount];
	}
	/**
	 * Expands the size of the polygon array
	 * @param newSize The new size of the polygon array
	 */
	public void expandPolygonArray(int newSize)
	{	
		if(!(newSize > polygonCount))
			return;		
		GLPolygon newArray[] = new GLPolygon[newSize];
		for(int i = 0; i < polygonCount; i++)
			newArray[i] = polygon[i];
		polygonCount = newSize;	
		polygon = newArray;
	}
	/**
	 * Returns the polygon from the array
	 * @param pIndex Array index of the polygon
	 * @return Polygon that existed as that array element
	 */
	public GLPolygon getPolygon(int pIndex)
	{
		return polygon[pIndex];
	}
	/**
	 * Adds a polygon to the array
	 * @param newPolygon Polygon to add
	 */
	public void addPolygon(GLPolygon newPolygon)
	{
		for(int i = 0; i < polygonCount; i++)
		{
			if(polygon[i] == null)
			{
				polygon[i] = newPolygon;
							return;
			}
		}
	}
	/**
	 * Draws each polygon
	 * @param gl OpenGL object to use for drawing
	 */
	public void render(GL gl) 
	{
		for(int i = 0; i < polygonCount; i++)
		{
			if(polygon[i] != null)
			{
				if(polygon[i].renderState != GL.GL_NONE && beginDraw)		
				{
					gl.glBegin(polygon[i].renderState)	;
					gl.glEnable(GL.GL_BLEND);
					gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
				}
					polygon[i].render(gl);	
				if(polygon[i].renderState != GL.GL_NONE && endDraw)
				{
					gl.glEnd();
					gl.glDisable(GL.GL_BLEND);
				}
			}
		}
	}
	/**
	 * Overwrites an array element with a specific polygon
	 * @param pIndex Index of the polygon in the array
	 * @param polygon Polygon to use
	 */
	public void setPolygon(int pIndex, GLPolygon polygon)
	{
		this.polygon[pIndex] = polygon;
	}
	public void setIsSequence(boolean firstElement, boolean lastElement)
	{
		this.beginDraw 	= firstElement;
		this.endDraw	= lastElement;
	}
}
